freeze.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. from __future__ import absolute_import
  2. import collections
  3. import logging
  4. import os
  5. from pip._vendor import six
  6. from pip._vendor.packaging.utils import canonicalize_name
  7. from pip._vendor.pkg_resources import RequirementParseError
  8. from pip._internal.exceptions import BadCommand, InstallationError
  9. from pip._internal.req.constructors import (
  10. install_req_from_editable,
  11. install_req_from_line,
  12. )
  13. from pip._internal.req.req_file import COMMENT_RE
  14. from pip._internal.utils.direct_url_helpers import (
  15. direct_url_as_pep440_direct_reference,
  16. dist_get_direct_url,
  17. )
  18. from pip._internal.utils.misc import (
  19. dist_is_editable,
  20. get_installed_distributions,
  21. )
  22. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  23. if MYPY_CHECK_RUNNING:
  24. from typing import (
  25. Iterator, Optional, List, Container, Set, Dict, Tuple, Iterable, Union
  26. )
  27. from pip._internal.cache import WheelCache
  28. from pip._vendor.pkg_resources import (
  29. Distribution, Requirement
  30. )
  31. RequirementInfo = Tuple[Optional[Union[str, Requirement]], bool, List[str]]
  32. logger = logging.getLogger(__name__)
  33. def freeze(
  34. requirement=None, # type: Optional[List[str]]
  35. find_links=None, # type: Optional[List[str]]
  36. local_only=False, # type: bool
  37. user_only=False, # type: bool
  38. paths=None, # type: Optional[List[str]]
  39. isolated=False, # type: bool
  40. wheel_cache=None, # type: Optional[WheelCache]
  41. exclude_editable=False, # type: bool
  42. skip=() # type: Container[str]
  43. ):
  44. # type: (...) -> Iterator[str]
  45. find_links = find_links or []
  46. for link in find_links:
  47. yield '-f {}'.format(link)
  48. installations = {} # type: Dict[str, FrozenRequirement]
  49. for dist in get_installed_distributions(
  50. local_only=local_only,
  51. skip=(),
  52. user_only=user_only,
  53. paths=paths
  54. ):
  55. try:
  56. req = FrozenRequirement.from_dist(dist)
  57. except RequirementParseError as exc:
  58. # We include dist rather than dist.project_name because the
  59. # dist string includes more information, like the version and
  60. # location. We also include the exception message to aid
  61. # troubleshooting.
  62. logger.warning(
  63. 'Could not generate requirement for distribution %r: %s',
  64. dist, exc
  65. )
  66. continue
  67. if exclude_editable and req.editable:
  68. continue
  69. installations[req.canonical_name] = req
  70. if requirement:
  71. # the options that don't get turned into an InstallRequirement
  72. # should only be emitted once, even if the same option is in multiple
  73. # requirements files, so we need to keep track of what has been emitted
  74. # so that we don't emit it again if it's seen again
  75. emitted_options = set() # type: Set[str]
  76. # keep track of which files a requirement is in so that we can
  77. # give an accurate warning if a requirement appears multiple times.
  78. req_files = collections.defaultdict(list) # type: Dict[str, List[str]]
  79. for req_file_path in requirement:
  80. with open(req_file_path) as req_file:
  81. for line in req_file:
  82. if (not line.strip() or
  83. line.strip().startswith('#') or
  84. line.startswith((
  85. '-r', '--requirement',
  86. '-f', '--find-links',
  87. '-i', '--index-url',
  88. '--pre',
  89. '--trusted-host',
  90. '--process-dependency-links',
  91. '--extra-index-url',
  92. '--use-feature'))):
  93. line = line.rstrip()
  94. if line not in emitted_options:
  95. emitted_options.add(line)
  96. yield line
  97. continue
  98. if line.startswith('-e') or line.startswith('--editable'):
  99. if line.startswith('-e'):
  100. line = line[2:].strip()
  101. else:
  102. line = line[len('--editable'):].strip().lstrip('=')
  103. line_req = install_req_from_editable(
  104. line,
  105. isolated=isolated,
  106. )
  107. else:
  108. line_req = install_req_from_line(
  109. COMMENT_RE.sub('', line).strip(),
  110. isolated=isolated,
  111. )
  112. if not line_req.name:
  113. logger.info(
  114. "Skipping line in requirement file [%s] because "
  115. "it's not clear what it would install: %s",
  116. req_file_path, line.strip(),
  117. )
  118. logger.info(
  119. " (add #egg=PackageName to the URL to avoid"
  120. " this warning)"
  121. )
  122. else:
  123. line_req_canonical_name = canonicalize_name(
  124. line_req.name)
  125. if line_req_canonical_name not in installations:
  126. # either it's not installed, or it is installed
  127. # but has been processed already
  128. if not req_files[line_req.name]:
  129. logger.warning(
  130. "Requirement file [%s] contains %s, but "
  131. "package %r is not installed",
  132. req_file_path,
  133. COMMENT_RE.sub('', line).strip(),
  134. line_req.name
  135. )
  136. else:
  137. req_files[line_req.name].append(req_file_path)
  138. else:
  139. yield str(installations[
  140. line_req_canonical_name]).rstrip()
  141. del installations[line_req_canonical_name]
  142. req_files[line_req.name].append(req_file_path)
  143. # Warn about requirements that were included multiple times (in a
  144. # single requirements file or in different requirements files).
  145. for name, files in six.iteritems(req_files):
  146. if len(files) > 1:
  147. logger.warning("Requirement %s included multiple times [%s]",
  148. name, ', '.join(sorted(set(files))))
  149. yield(
  150. '## The following requirements were added by '
  151. 'pip freeze:'
  152. )
  153. for installation in sorted(
  154. installations.values(), key=lambda x: x.name.lower()):
  155. if installation.canonical_name not in skip:
  156. yield str(installation).rstrip()
  157. def get_requirement_info(dist):
  158. # type: (Distribution) -> RequirementInfo
  159. """
  160. Compute and return values (req, editable, comments) for use in
  161. FrozenRequirement.from_dist().
  162. """
  163. if not dist_is_editable(dist):
  164. return (None, False, [])
  165. location = os.path.normcase(os.path.abspath(dist.location))
  166. from pip._internal.vcs import vcs, RemoteNotFoundError
  167. vcs_backend = vcs.get_backend_for_dir(location)
  168. if vcs_backend is None:
  169. req = dist.as_requirement()
  170. logger.debug(
  171. 'No VCS found for editable requirement "%s" in: %r', req,
  172. location,
  173. )
  174. comments = [
  175. '# Editable install with no version control ({})'.format(req)
  176. ]
  177. return (location, True, comments)
  178. try:
  179. req = vcs_backend.get_src_requirement(location, dist.project_name)
  180. except RemoteNotFoundError:
  181. req = dist.as_requirement()
  182. comments = [
  183. '# Editable {} install with no remote ({})'.format(
  184. type(vcs_backend).__name__, req,
  185. )
  186. ]
  187. return (location, True, comments)
  188. except BadCommand:
  189. logger.warning(
  190. 'cannot determine version of editable source in %s '
  191. '(%s command not found in path)',
  192. location,
  193. vcs_backend.name,
  194. )
  195. return (None, True, [])
  196. except InstallationError as exc:
  197. logger.warning(
  198. "Error when trying to get requirement for VCS system %s, "
  199. "falling back to uneditable format", exc
  200. )
  201. else:
  202. if req is not None:
  203. return (req, True, [])
  204. logger.warning(
  205. 'Could not determine repository location of %s', location
  206. )
  207. comments = ['## !! Could not determine repository location']
  208. return (None, False, comments)
  209. class FrozenRequirement(object):
  210. def __init__(self, name, req, editable, comments=()):
  211. # type: (str, Union[str, Requirement], bool, Iterable[str]) -> None
  212. self.name = name
  213. self.canonical_name = canonicalize_name(name)
  214. self.req = req
  215. self.editable = editable
  216. self.comments = comments
  217. @classmethod
  218. def from_dist(cls, dist):
  219. # type: (Distribution) -> FrozenRequirement
  220. # TODO `get_requirement_info` is taking care of editable requirements.
  221. # TODO This should be refactored when we will add detection of
  222. # editable that provide .dist-info metadata.
  223. req, editable, comments = get_requirement_info(dist)
  224. if req is None and not editable:
  225. # if PEP 610 metadata is present, attempt to use it
  226. direct_url = dist_get_direct_url(dist)
  227. if direct_url:
  228. req = direct_url_as_pep440_direct_reference(
  229. direct_url, dist.project_name
  230. )
  231. comments = []
  232. if req is None:
  233. # name==version requirement
  234. req = dist.as_requirement()
  235. return cls(dist.project_name, req, editable, comments=comments)
  236. def __str__(self):
  237. # type: () -> str
  238. req = self.req
  239. if self.editable:
  240. req = '-e {}'.format(req)
  241. return '\n'.join(list(self.comments) + [str(req)]) + '\n'